import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/ex/build_context_ex.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../resources/kq_theme_colors.dart';
import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 选择组件
///
/// [ItemType.select]
///
/// 结合 KqFormEntity 使用
///
/// @author 周卓
///
class KqSelectItemView extends StatefulWidget {
  final KqFormEntity entity;

  /// 输入控件或选择控件的左侧控件
  final Widget Function(KqFormEntity entity)? customLeftView;

  /// 输入控件或选择控件或自定义控件的右侧控件
  final Widget Function(KqFormEntity entity)? customRightView;

  /// 选择控件箭头右侧的自定义控件
  final Widget Function(KqFormEntity entity)? customSelectArrowRightView;

  /// 自定义控件的底部控件
  final Widget Function(KqFormEntity entity)? customBottomView;

  /// 选择控件点击回调
  final Function(KqFormEntity entity)? onTap;

  /// 自定义或选择控件的标题点击回调
  final Function(KqFormEntity entity)? onTitleTap;

  const KqSelectItemView(
      {Key? key,
      required this.entity,
      this.onTap,
      this.onTitleTap,
      this.customLeftView,
      this.customRightView,
      this.customSelectArrowRightView,
      this.customBottomView})
      : super(key: key);

  @override
  KqSelectItemViewState createState() => KqSelectItemViewState();
}

class KqSelectItemViewState extends State<KqSelectItemView> {
  /// 画笔，用于测量
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);

  @override
  void initState() {
    widget.entity.widgetState = this;
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  /// 获取1行高度
  double measureTextHeight(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.height;
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    var titleTextStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize:
                KqThemeManager.instance.getConfig().formConfig.titleFontSize ??
                    16.sp,
            color: widget.entity.titleColor ??
                KqThemeManager.getFormConfig().titleTextColor ??
                KqThemeColors.text26);
    // 一行标题的高度
    var titleOneLineHeight =
        measureTextHeight(widget.entity.title, textStyle: titleTextStyle);
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ??
        KqThemeManager.getFormConfig().backgroundColor ??
        KqThemeColors.bgWhite;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          KqInkWell(
            onTap: widget.entity.forceOnTap || widget.entity.isEditable()
                ? () {
                    TextFiledUtil.clearFocus(context);
                    if (widget.entity.onTap != null) {
                      widget.entity.onTap!(widget.entity);
                    }
                    if (widget.onTap != null) {
                      widget.onTap!(widget.entity);
                    }
                  }
                : null,
            backgroundColor: bgColor,
            child: Opacity(
              opacity: widget.entity.opacity,
              child: Container(
                padding: EdgeInsets.only(
                    right: widget.entity.paddingHorizontal ??
                        KqThemeManager.instance
                            .getConfig()
                            .formConfig
                            .paddingHorizontal ??
                        16.r),
                decoration: widget.entity.showFocusBorder
                    ? BoxDecoration(
                        color: bgColor,
                        border: Border.all(width: 1, color: KqThemeColors.bgBlue))
                    : null,
                child: Row(
                  crossAxisAlignment: widget.entity.multiline
                      ? CrossAxisAlignment.baseline
                      : CrossAxisAlignment.center,
                  textBaseline:
                      widget.entity.multiline ? TextBaseline.alphabetic : null,
                  children: <Widget>[
                    KqInkWell(
                      onTap: widget.entity.onTitleTap != null ||
                              widget.onTitleTap != null
                          ? () {
                              widget.entity.onTitleTap?.call(widget.entity);
                              widget.onTitleTap?.call(widget.entity);
                            }
                          : null,
                      child: Container(
                        padding: EdgeInsets.only(
                            right: widget.entity.titleRightMargin ??
                                (widget.entity.title.isNotEmpty ? 10.r : 0),
                            top: widget.entity.paddingVertical ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingVertical ??
                                15.r,
                            bottom: widget.entity.paddingVertical ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingVertical ??
                                15.r),
                        child: Row(
                          children: <Widget>[
                            /// 是否必填
                            Container(
                              alignment: Alignment.centerRight,
                              width: widget.entity.paddingHorizontal ??
                                  KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .paddingHorizontal ??
                                  16.r,
                              padding: EdgeInsets.only(right: 2.r),
                              child: Text(
                                "∗",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontSize: KqThemeManager.instance
                                            .getConfig()
                                            .formConfig
                                            .mustInputFontSize ??
                                        14.sp,
                                    color: widget.entity.mustInput
                                        ? KqThemeColors.textRed
                                        : KqThemeColors.bgTransparent),
                              ),
                            ),

                            /// 标题
                            if (widget.entity.title.isNotEmpty)
                              LimitedBox(
                                maxWidth: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .titleMaxWidth ??
                                    200.r,
                                child: Text(
                                  widget.entity.title,
                                  style: titleTextStyle,
                                ),
                              )
                          ],
                        ),
                      ),
                    ),

                    /// 右侧文字
                    Expanded(
                      child: Row(
                        children: [
                          /// 左边自定义控件
                          /// 自定义布局，来自实体类
                          widget.entity.customLeftView != null
                              ? widget.entity.customLeftView!(widget.entity)
                              : Container(),

                          /// 自定义布局，来自控件
                          widget.customLeftView != null
                              ? widget.customLeftView!(widget.entity)
                              : Container(),

                          // 为了和UI规范的标题和内容之间距离40
                          SizedBox(
                            width: 30.r,
                            height: 1.r,
                          ),

                          Expanded(
                            child: Padding(
                              padding: EdgeInsets.symmetric(
                                  vertical: widget.entity.paddingVertical ??
                                      KqThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .paddingVertical ??
                                      15.r),
                              child: Text(
                                widget.entity.valueForShow ??
                                    (widget.entity.hint ?? ''),
                                textAlign: TextAlign.right,
                                overflow: widget.entity.overflow ??
                                    (!widget.entity.multiline
                                        ? TextOverflow.ellipsis
                                        : null),
                                maxLines: widget.entity.multiline
                                    ? widget.entity.maxLines
                                    : 1,
                                style: TextStyle(
                                  color: widget.entity.valueForShow != null
                                      ? widget.entity.contentColor ??
                                          KqThemeManager.getFormConfig()
                                              .contentTextColor ??
                                          KqThemeColors.text59
                                      : KqThemeColors.textBF,
                                  fontSize: KqThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .contentFontSize ??
                                      16.sp,
                                ),
                              ),
                            ),
                          ),
                          Text(
                            widget.entity.unit ?? '',
                            textAlign: TextAlign.right,
                            style: TextStyle(
                              color: widget.entity.contentColor ??
                                  KqThemeColors.text59,
                              fontSize: KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .contentFontSize ??
                                  16.sp,
                            ),
                          )
                        ],
                      ),
                    ),

                    /// 自定义布局
                    widget.entity.customRightView != null
                        ? widget.entity.customRightView!(widget.entity)
                        : Container(),

                    /// 自定义布局
                    widget.customRightView != null
                        ? widget.customRightView!(widget.entity)
                        : Container(),

                    /// 右侧箭头
                    Visibility(
                        visible: widget.entity.isEditable(),
                        child: Container(
                            padding: EdgeInsets.only(left: 4.r),
                            margin: EdgeInsets.only(
                              top: widget.entity.multiline
                                  ? (widget.entity.paddingVertical ??
                                      KqThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .paddingVertical ??
                                      15.r)
                                  : 0,
                            ),
                            width: titleOneLineHeight,
                            height: titleOneLineHeight,
                            alignment: Alignment.center,
                            child: Image.asset(
                              Images.commonIcJiantouRight16,
                              width: 16.r,
                              height: 16.r,
                              fit: BoxFit.fitWidth,
                              package: KqGlobal.packageName,
                            ))),

                    if (widget.entity.customSelectArrowRightView != null ||
                        widget.customSelectArrowRightView != null)
                      SizedBox(
                        width: 8.r,
                      ),

                    /// 自定义布局
                    widget.entity.customSelectArrowRightView != null
                        ? widget.entity.customSelectArrowRightView!(widget.entity)
                        : Container(),

                    /// 自定义布局
                    widget.customSelectArrowRightView != null
                        ? widget.customSelectArrowRightView!(widget.entity)
                        : Container(),
                  ],
                ),
              ),
            ),
          ),

          /// 自定义底部控件，来自实体类
          widget.entity.customBottomView != null
              ? widget.entity.customBottomView!(widget.entity)
              : Container(),

          /// 自定义控件，来自控件
          widget.customBottomView != null
              ? widget.customBottomView!(widget.entity)
              : Container(),

          /// 分割线
          Visibility(
              visible: !widget.entity.hideDivider,
              child: KqDivider(
                leftMargin: !widget.entity.dividerHorMarginEnable
                    ? 0
                    : widget.entity.paddingHorizontal ??
                        KqThemeManager.instance
                            .getConfig()
                            .formConfig
                            .paddingHorizontal ??
                        16.r,
                rightMargin: !widget.entity.dividerHorMarginEnable
                    ? 0
                    : widget.entity.paddingHorizontal ??
                        KqThemeManager.instance
                            .getConfig()
                            .formConfig
                            .paddingHorizontal ??
                        16.r,
              ))
        ],
      ),
    );
  }
}
